//
//  NSString+Method.m
//  SegmentDemo
//
//  Created by 塔兮 on 2022/4/11.
//

#import "NSString+Method.h"

@implementation NSString (Method)

- (UIColor *)RGBAColorWithHEXString {
    NSString *hexString = self;
    hexString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    UIColor *defaultColor = [UIColor clearColor];
    
    if (hexString.length < 6) return defaultColor;
    if ([hexString hasPrefix:@"#"]) hexString = [hexString substringFromIndex:1];
    if ([hexString hasPrefix:@"0X"]) hexString = [hexString substringFromIndex:2];
    if (hexString.length != 6) return defaultColor;
    
    //method1
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    unsigned int hexNumber;
    if (![scanner scanHexInt:&hexNumber]) return defaultColor;
    
    if (hexNumber > 0xFFFFFF) return defaultColor;
    
    CGFloat red   = ((hexNumber >> 16) & 0xFF);
    CGFloat green = ((hexNumber >> 8) & 0xFF);
    CGFloat blue  = (hexNumber & 0xFF);
    
    return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];
}

- (CGFloat)textHeightWithFont:(UIFont *)font maxWidth:(CGFloat)width {
    CGRect rect = [self boundingRectWithSize:CGSizeMake(width, 99999)
                                     options:(NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin)
                                  attributes:@{NSFontAttributeName: font}
                                     context:nil];
    return rect.size.height;
}

- (CGFloat)textWidthWithFont:(UIFont *)font maxHeight:(CGFloat)height {
    CGRect rect = [self boundingRectWithSize:CGSizeMake(999999, height)
                                     options:(NSStringDrawingUsesLineFragmentOrigin)
                                  attributes:@{NSFontAttributeName: font}
                                     context:nil];
    return rect.size.width;
}

@end
